package fail

import (
	"fmt"
	"os"
)

var (
	EnvDebugOnError string = "CLIUTILS_DEBUG"
)

var (
	debug = 0
)

func init() {
	switch env := os.Getenv(EnvDebugOnError); env {
	case "", "0", "false", "off":
	case "1", "true", "on":
		debug = 1
	case "2":
		debug = 2
	default:
		debug = 1
	}
}

func WhenFunc(err error, fn func(err error) bool) {
	if fn(err) {
		if debug > 0 {
			panic(err) // TODO show more info according to `debug`
		}
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func When(err error) {
	WhenFunc(err, func(err error) bool { return err != nil })
}
